package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取resuqst 和response对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //2. 获取请求的路径 判断是否是登录 如果是则放行
        if(request.getURI().getPath().contains("/login_auth")){
            return chain.filter(exchange);
        }

        //3. 从请求头里面获取用户的token 如果为空则返回401
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4. 解析和判断token 如果不合法或者过期返回401
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);

        int status = AppJwtUtil.verifyToken(claimsBody);
        if(1 == status || 2 == status){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //对请求进行增强
        String userId = claimsBody.get("id").toString();

        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.set("userId", userId);
        }).build();

        exchange = exchange.mutate().request(serverHttpRequest).build();

        //5. 如果合法则放行
        return chain.filter(exchange);
    }

    /*
    返回一个排序的数字 数字越小 优先级越高
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
